package io.read;

import io.FileDemo;

import java.io.*;

public class InputStreamReaderDemo {
    public static void main(String[] args) throws IOException {
        String p = FileDemo.getJavaFilePath(FileReaderDemo.class, "") + "/../1.txt";
//        System.out.println(read(p));
        System.out.println(read(new char[20],0,9, p));
    }

    /**
     * 将字符读进数组的一部分
     * @param cbuf
     * @param offset
     * @param length
     * @param filePath
     * @return
     */
    public static String read(char cbuf[], int offset,int length,String filePath) {
        StringBuffer sb = new StringBuffer();
        int charactersNumber = 0;
        int n = 0;
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader =  new InputStreamReader(new FileInputStream(filePath));
            while ((charactersNumber = inputStreamReader.read(cbuf,offset,length)) != -1) {
                System.out.println("读取的字符个数:" + charactersNumber);
                sb.append(new String(cbuf, 0, charactersNumber));
                n += charactersNumber;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            inputStreamReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("字符总数:" + n);
        return sb.toString();
    }

    /**
     * 一次读一个字符
     *
     * @param filePath
     */
    public static String read(String filePath) {
        InputStreamReader inputStreamReader = null;
        StringBuffer sb = new StringBuffer();
        try {
            inputStreamReader = new InputStreamReader(new FileInputStream(filePath));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        int ch = 0;
        int n = 0;
        try {
            while ((ch = inputStreamReader.read()) != -1) {
                sb.append((char) ch);
                n++;
            }
        } catch (IOException e) {
        }
        try {
            inputStreamReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("字符总数:" + n);
        return sb.toString();
    }
}
